﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;

namespace Ledict.ConditionExtract.Frm.Base
{
    /// <summary>
    /// 节点选择窗体
    /// </summary>
    public partial class FrmNodeSelect : BaseForm
    {
        #region 公有变量

        readonly TreeDataBLL trbll = new TreeDataBLL();

        readonly RegexParse.RegexParse getregex = new RegexParse.RegexParse();

        /// <summary>
        /// 案由名称，默认刑事树
        /// </summary>
        public string TypeName = "刑事罪名";//默认刑事树

        private TreeNode _clicknode;//点击节点树后，保存该节点
        private List<TreeNode> NodeList = new List<TreeNode>();//节点树上显示出来的所有节点集合
        private readonly List<TreeNode> _sourceNodeList = new List<TreeNode>(); //来源树中显示出来的所有节点集合

        public string FirId = "1000";//默认刑事树ID
        public string LocateNode = "";//定位节点
        //SYS_ArgumentType argumenttypeModel;//字典值
        //int RowIndex = -1;
        DataTable Querydt;//查询结果集
        #endregion


        public FrmNodeSelect()
        {
            InitializeComponent();
        }

        private void FrmNodeSelect_Load(object sender, EventArgs e)
        {
            //TypeName = "刑事罪名";
            CaseCauseTree(TypeName);
        }

        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeBtn_Click(object sender, EventArgs e)
        {
            QueryNode();
        }

        /// <summary>
        /// 开始查询
        /// </summary>
        private void QueryNode()
        {
            var queryNodeName = QueryNodeTxt.Text.Trim();//查询关键字
            if (queryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, queryNodeName, 1);//查询结果
                MaxCount.Text = Querydt.Rows.Count.ToString();//总数
                if (Querydt.Rows.Count > 0)
                {
                    CurrentCount.Text = "1";//当前节点条数
                    SkipNumber.Text = CurrentCount.Text;//跳转文本框
                    var currNode = Convert.ToInt32(CurrentCount.Text);//当前节点条数
                    LinkIsVisible(currNode);//上一条下一条是否可用
                    QueryNode_Page(Querydt, currNode);//定位到目标节点
                }
                else
                {
                    CurrentCount.Text = "0";//没结果
                    SkipNumber.Text = CurrentCount.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }

        /// <summary>
        /// 回车查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')//回车
            {
                QueryNode();
            }
        }

        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) + 1).ToString();//下一条
            SkipNumber.Text = CurrentCount.Text;
            var currNode = Convert.ToInt32(CurrentCount.Text);
            QueryNode_Page(Querydt, currNode);//定位查询
            LinkIsVisible(currNode);
        }

        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) - 1).ToString();//上一条
            SkipNumber.Text = CurrentCount.Text;
            var currNode = Convert.ToInt32(CurrentCount.Text);
            QueryNode_Page(Querydt, currNode);//定位查询
            LinkIsVisible(currNode);
        }

        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="currNode"></param>
        private void LinkIsVisible(int currNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (currNode <= 1)//当前小于1
            {
                Prelinkbtn.Enabled = false;//上一页不可用
            }
            if (currNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;//下一页不可用
            }

        }

        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var currNode = Convert.ToInt32(SkipNumber.Text);//当前节点条数
            if (Querydt.Rows.Count >= currNode)
            {
                CurrentCount.Text = SkipNumber.Text;//跳转
                QueryNode_Page(Querydt, currNode);//定位到目标节点
                LinkIsVisible(currNode);// 上一条下一条是否可用
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }

        }
        #endregion

        #region 树选择

        /// <summary>
        /// 定位到目标节点
        /// </summary>
        /// <param name="dt">查询返回结果集</param>
        /// <param name="showindex">第几条</param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                var notePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');//所有父级
                for (var i = 0; i < notePidArr.Length; i++)
                {
                    if (i != notePidArr.Length - 1)
                    {
                        var node = FindNode(notePidArr[i]);
                        if (node != null)
                        {
                            node.Expand();//拖出所有父级节点
                        }
                    }
                    else  //最后一级节点为查找节点
                    {
                        var node = FindNode(notePidArr[i]);
                        tVCaseCause.SelectedNode = node;//定位
                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }
        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="id"></param>
        private void ToLocateNode(string id)
        {
            var notePidArr = getregex.GetParseValue("CC1509171748560001", trbll.GetAllParentNode(id)).Split(',');//去掉多余逗号 ;
            for (var i = 0; i < notePidArr.Length; i++)
            {
                if (i != notePidArr.Length - 1)
                {
                    FindNode(notePidArr[i]).Expand();
                }
                else
                {
                    var node = FindNode(notePidArr[i]);
                    tVCaseCause.SelectedNode = node;
                }
            }

        }

        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="nodeid">节点ID</param>
        /// <returns></returns>
        private TreeNode FindNode(string nodeid)
        {
            foreach (var node in NodeList)//遍历现在界面上的所有节点
            {
                if (node.Tag.ToString() == nodeid)
                {
                    return node;
                }
            }
            return null;

        }

        /// <summary>
        /// 案由树（第一级）
        /// </summary>
        public void CaseCauseTree(string typeName)
        {
            #region 初始化
            tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            #endregion
            var dt = trbll.NodeTree_Tree("");//第一层的树
            var arrayDr = dt.Select("name='" + typeName + "'");//找出“指定案由名称”的节点
            foreach (var caseTreeNodeRode in arrayDr)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode[1]);
                node.Tag = caseTreeNodeRode[0];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode[2]);
                FirId = caseTreeNodeRode[0].ToString();
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有没有下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                tVCaseCause.Nodes.Add(node);//父级节点添加节点
                if (caseTreeNodeRode["CC_CommonCase"].ToString() == "1")//同案节点标颜色
                    node.ForeColor = Color.Blue;
                NodeList.Add(node);//list用来查询
            }
        }

        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();// 父级ID
            var caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有无下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                if (caseTreeNodeRode.Rows[i]["CC_CommonCase"].ToString() == "1")//同案节点标颜色
                    node.ForeColor = Color.Blue;
                parentNode.Nodes.Add(node);//父级节点添加节点
                NodeList.Add(node);//list用来查询
            }
        }

        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild(e.Node);
        }
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (_clicknode != null && _clicknode.ForeColor != Color.Blue)
                _clicknode.ForeColor = Color.Black;
            _clicknode = e.Node;//保存节点
            if (_clicknode.ForeColor != Color.Blue)
                _clicknode.ForeColor = Color.Red;



        }
        #endregion

        /// <summary>
        /// 双击确认选择节点并关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_DoubleClick(object sender, EventArgs e)
        {
            var node = tVCaseCause.SelectedNode;
            this.Tag = node.Tag + "," + node.Text;
            DialogResult = DialogResult.OK;
        }





    }
}
